# -*- coding:utf-8 -*-

from server.action.batchBase import batchBase
from server.util import sqlBuild, stringUtil
import uuid


class extr(batchBase):  # 单任务获取
    @batchBase.idChecked
    def action(self, data, d):
        baId = data[0]
        ss = stringUtil.redis_key_name(baId, "ss")
        rl = stringUtil.redis_key_name(baId, "rl")
        ml = stringUtil.redis_key_name(baId, "ml")
        bel = stringUtil.redis_key_name(baId, "be")
        arg = self.re.zrange(ss, 0, 0, withscores=True)  # 将存在于redis的任务取出一条

        if arg:
            command, count = arg[0]
            arr = command.split(",")
            if arr[1][-2:] == "on" or arr[1][-2:] == "of":  # 命令最后两位是开关灯命令
                self.re.zadd(rl, command, int(count) + 1)  # 存入基站的已完成任务列表
            else:  # 存入任务集散中心
                self.re.zadd(ml, command, int(count) + 1)  # 任务id, 命令集

            # self.re.zadd(ml, str(int(taskId)) + "," + command, )  # 任务id, 命令集

            # 将任务从待执行列表中删除
            self.re.zrem(ss, command)
            self.re.set(bel, 0)  # 将bell计时标为0

            d.callback((1, (command,), baId))
        else:  # 返回over
            lb = stringUtil.redis_key_name(baId)
            self.re.lset(lb, 1, 0)  # 将心跳更新为0
            self.re.set(bel, 0)  # 将bell计时标为0

            d.callback((1, (baId, "over",), baId))
